unit UDlg_MultiSelection;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls, Buttons, CheckLst;

type
  TFDlg_MultiSelection = class(TForm)
    CheckListBox1: TCheckListBox;
    BitBtn1: TBitBtn;
    BitBtn2: TBitBtn;
  private
    function GetItems: TStrings;
    procedure SetSelectedText(Value: string);
    procedure SetSelectedValue(const Value: Cardinal);
    function GetSelectedText: string;
    function GetSelectedValue: Cardinal;
    { Private declarations }
  public
    { Public declarations }
  published
    property SelectedValue: Cardinal read GetSelectedValue write SetSelectedValue;
    property SelectedText: string read GetSelectedText write SetSelectedText;
    property Items: TStrings read GetItems;
  end;

var
  FDlg_MultiSelection: TFDlg_MultiSelection;

implementation

{$R *.dfm}

{ TFDlg_MultiSelection }

function TFDlg_MultiSelection.GetItems: TStrings;
begin
  Result:= CheckListBox1.Items;
end;

function TFDlg_MultiSelection.GetSelectedText: string;
var
  I: Integer;
begin
  Result:= '';
  for I := 0 to CheckListBox1.Items.Count - 1 do
    if CheckListBox1.Checked[I] then
      Result:= Result + ',' + CheckListBox1.Items[I];
  if Result <> '' then
    Delete(Result, 1, 1);
end;

function TFDlg_MultiSelection.GetSelectedValue: Cardinal;
var
  I: Integer;
  V: Int64;
begin
  Result:= 0;
  V:= 1;
  for I := 0 to CheckListBox1.Items.Count - 1 do begin
    if CheckListBox1.Checked[I] then
      Result:= Result + V;
    V:= V * 2;
  end;
end;

procedure TFDlg_MultiSelection.SetSelectedText(Value: string);
var
  P: Integer;
begin
  P:= Pos(',', Value);
  CheckListBox1.CheckAll(cbUnchecked);
  while P > 0 do begin
    CheckListBox1.Checked[CheckListBox1.Items.IndexOf(Copy(Value, 1, P - 1))]:= True;
    Delete(Value, 1, P);
    P:= Pos(',', Value);
  end;
  CheckListBox1.Checked[CheckListBox1.Items.IndexOf(Value)]:= True;
end;

procedure TFDlg_MultiSelection.SetSelectedValue(const Value: Cardinal);
var
  I: Integer;
  V: Int64;
begin
  V:= 1;
  CheckListBox1.CheckAll(cbUnchecked);
  for I := 0 to CheckListBox1.Items.Count - 1 do begin
    CheckListBox1.Checked[I]:= V and Value > 0;
    V:= V * 2;
  end;
end;

end.
